package com.neomanager.common.web;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import sun.misc.BASE64Encoder;

import com.neomanager.common.dao.CommonDao;
import com.util.FileUtil;
import com.util.SHA256;
import com.util.UtilCommon;

@SuppressWarnings("restriction")
@Controller
public class CommonController
{
	private final Logger logger = Logger.getLogger(this.getClass());
	
	@Resource(name="CommonDao")
	CommonDao commonDao;

	/**
	 * 이미지 업로드
	 */
	@RequestMapping(value = "/common/imageupload.do", method = RequestMethod.POST)
	public String processImageUpload(@RequestParam Map<String, Object> commandMap, Model model,
			HttpServletRequest request, HttpServletResponse response
			)  throws Exception
	{
		logger.debug("에디터 이미지 업로드");

		// 폴더 파일 저장
		Properties props = new Properties();
		props.load(new java.io.BufferedInputStream( getClass().getClassLoader().getResourceAsStream("config.properties")) );
		String strFilePath = props.getProperty("uploadsDir").trim();

		String pathUrl = "/uploads/editor";
		strFilePath = strFilePath + File.separator + "editor";
		
        // 폴더 파일 저장
		//String pathUrl = "/uploads/editor";
		//String strFilePath = request.getSession().getServletContext().getRealPath("") + File.separator +  ("uploads") + File.separator + "editor";

		Map<String, Map<String, String>> fileInfoMap = FileUtil.doMultiFileUpLoad(request, strFilePath, pathUrl);
        logger.debug(fileInfoMap);

    	String fileurl  = "";
    	String message  = "";
        String fileName = "";
    	String result_str = "";
		if (fileInfoMap != null)
		{
		    Iterator<String> iterator = fileInfoMap.keySet().iterator();
		    while (iterator.hasNext())
		    {
		        Map<String, String> fileMap = new HashMap<String, String>();
		        String key = iterator.next();
		        fileMap = fileInfoMap.get(key);

				fileName = fileMap.get("FILERENAME");

				message = "이미지 업로드 완료";
				fileurl = fileMap.get("FILEURLPATH") + fileMap.get("FILERENAME");
				result_str = "{\"success\":true,\"file_url\":\""+UtilCommon.host+fileurl+"\",\"message\":\""+message+"\"}";
		    }
		}
        logger.debug(fileName);

		model.addAttribute("result_str", result_str);
		model.addAttribute("fileName", fileName);
		return "common/image";
	}

	/**
	 * 첨부파일 다운로드
	 */
	@RequestMapping(value = "/common/download.do", method = RequestMethod.GET)
    public void processFildDownload(@RequestParam Map<String, Object> commandMap, HttpServletRequest request, HttpServletResponse response) throws Exception
    {
		logger.debug("첨부 파일 다운로드");

		commandMap.put("file_id", request.getParameter("fileid"));
		commandMap.put("file_job_id", request.getParameter("jobid"));

		// 파일 상세정보
		Map<String, Object> viewMap = commonDao.selectFileInfoView(commandMap);
		if (viewMap == null)
		{
			PrintWriter writer=response.getWriter();
            writer.println("<script type='text/javascript'>alert('no data.'); history.go(-1);</script>");
			return;
		}

		//저장된 파일 정보
	    String filepath       		= viewMap.get("FILE_PATH").toString();
	    String oldFileName    	= viewMap.get("FILE_NAME").toString();
	    String savedFileName  = viewMap.get("FILE_RENAME").toString();

		String filename 			= filepath+savedFileName;	// 새로운 파일 이름명
        String filename2 			= oldFileName; 					// 원본 파일 및 이름명

        File file = new File (filename);
        logger.debug("-------------- filename : " + filename);
		logger.debug("-------------- exists : " + file.exists());

		if (!file.exists())
        {
			PrintWriter writer=response.getWriter();
            writer.println("<script type='text/javascript'>alert('no file.'); history.go(-1);</script>");
			return;
        }

        filename2 = new String(filename2.getBytes("KSC5601"),"8859_1");

        //  Content-Disposition 헤더에 파일 이름 세팅.
        String strClient = request.getHeader("user-agent");
        if( strClient.indexOf("MSIE 5.5") != -1 )
        {
            response.setHeader("Content-Type", "doesn/matter;");
            response.setHeader("Content-Disposition", "filename=" + filename2 + ";");
        }
        else if (strClient.indexOf("MSIE 6.0") != -1)
        {
            response.setHeader("Content-Type", "application/octet-stream;");
            response.setHeader("Content-Disposition", "attachment;filename=" + filename2 + ";");
        }
        else
        {
            response.setHeader("Content-Type", "application/octet-stream;");
            response.setHeader("Content-Disposition", "attachment;filename=" + filename2 + ";");
        }

        byte b[] = new byte[(int)file.length()];

        BufferedInputStream fin = null;
        BufferedOutputStream outs = null;

        if (file.isFile())
        {
             fin = new BufferedInputStream(new FileInputStream(file));
             outs = new BufferedOutputStream(response.getOutputStream());
            int read = 0;
            while ((read = fin.read(b)) != -1)
            {
                outs.write(b,0,read);
            }
            outs.close();
            fin.close();
        }
    }

	/**
	 * 코멘트 등록
	 * @return
	 */
	@RequestMapping(value = "/common/commentInsert.do", method = RequestMethod.POST)
    public String processCommtInsert(
    		@RequestParam Map<String, Object> commandMap,
    		HttpServletRequest request,
    		HttpServletResponse response) throws Exception
    {
		logger.debug("코멘트 등록.");

		String returnUrl = commandMap.get("returnURL").toString();

		// 비밀번호 암호화
		String commt_pw = commandMap.get("commt_pw").toString();
		SHA256 s = new SHA256( commt_pw.getBytes() );
		BASE64Encoder Base64Encoder = new BASE64Encoder();
		commt_pw = Base64Encoder.encode(s.GetHashCode());

		// 코멘트 아이디 생성
		String commt_id = UtilCommon.idMake("");
		String job_id =  commandMap.get("bbs_id").toString();
		String relate_id = commandMap.get("article_id").toString();
		int commt_step = Integer.parseInt(commandMap.get("commt_step").toString());

		if(commt_step > 0){
			commt_step = commt_step + 1;
		}

		int commt_depth = Integer.parseInt(commandMap.get("commt_depth").toString());

		if(commt_depth > 0){
			commt_depth = commt_depth + 1;
		}

		commandMap.put("commt_id",commt_id);
		commandMap.put("job_id",job_id);
		commandMap.put("relate_id", relate_id);
		commandMap.put("commt_ref", commt_id);
		commandMap.put("commt_step", commt_step);
		commandMap.put("commt_depth", commt_depth);
		commandMap.put("commt_pw", commt_pw);

		commonDao.insertCommentInfo(commandMap);

		return returnUrl;
    }

	/**
	 * 코멘트 답글 등록
	 * @return
	 */
	@RequestMapping(value = "/common/commentReplyInsert.do", method = RequestMethod.POST)
    public String processCommtReplyInsert(
    		@RequestParam Map<String, Object> commandMap,
    		HttpServletRequest request,
    		HttpServletResponse response) throws Exception
    {
		logger.debug("코멘트 등록.");

		/*String relate_id = commandMap.get("relate_id").toString();
		String job_id = commandMap.get("job_id").toString();
		String commt_writer_id = commandMap.get("commt_writer_id").toString();
		String commt_writer = commandMap.get("commt_writer").toString();
		String commt_contents = commandMap.get("commt_contents").toString();*/
		String returnURL = commandMap.get("returnURL").toString();
		String commt_ref = commandMap.get("commt_ref").toString();
		String commt_step = commandMap.get("commt_step").toString();
		String commt_depth = commandMap.get("commt_depth").toString();
		String commt_pw = commandMap.get("commt_pw").toString();

		//비밀번호 암호화
		SHA256 s = new SHA256( commt_pw.getBytes() );
		BASE64Encoder Base64Encoder = new BASE64Encoder();
		commt_pw = Base64Encoder.encode(s.GetHashCode());


		//step + 1 update
		int step = Integer.parseInt(commt_step);
		int depth = Integer.parseInt(commt_depth);
		commandMap.put("commt_step",step);
		commandMap.put("commt_depth",depth);

		commonDao.updateCommentStep(commandMap);

		String id = UtilCommon.idMake("");
		commandMap.put("commt_id", id);
		commandMap.put("commt_ref", commt_ref);
		commt_step = Integer.toString(step + 1);
		commandMap.put("commt_step",commt_step);
		commt_depth = Integer.toString(depth + 1);
		commandMap.put("commt_depth",commt_depth);
		commandMap.put("commt_pw",commt_pw);

		commonDao.insertCommentInfo(commandMap);

		return returnURL;
    }

	/**
	 * 코멘트 삭제
	 * @return
	 */
	@RequestMapping(value = "/common/commentReplyDelete.do", method = RequestMethod.POST)
    public String processCommtDelete(
    		@RequestParam Map<String, Object> commandMap,
    		HttpServletRequest request,
    		HttpServletResponse response) throws Exception
    {
		logger.debug("코멘트 삭제.");

		String returnURL = commandMap.get("returnURL").toString();

		commonDao.deleteCommentInfo(commandMap);

		return returnURL;
    }
}

